package com.sxkf.core.common.ali;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.factory.Factory.Payment;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import org.jeecg.common.exception.SxkfException;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;


public class AliPayUtil {

    @PostConstruct
    public void init(){
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
    }
    public static String pay(String subject, String outTradeNo, BigDecimal totalAmount) {

        AlipayTradeAppPayResponse response = null;
        try {
            response = Payment.App().pay(subject, outTradeNo, String.valueOf(totalAmount.multiply(BigDecimal.valueOf(100))));
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new SxkfException(e.getMessage());
        }
        return response.body;
    }

    public static void refund(String outTradeNo, String refundAmount){
        try {
            Payment.Common().refund(outTradeNo, refundAmount);
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new SxkfException(e.getMessage());
        }
    }

    private static Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipay.com";
        config.signType = "RSA2";
        config.appId = AliConstants.ALI_APP_ID;
        config.merchantPrivateKey = AliConstants.PRIVATE_KEY;
        config.alipayPublicKey = AliConstants.PublicKey;
        config.notifyUrl = AliConstants.NOTIFY_URL;
        config.encryptKey = AliConstants.ENCRYPT_KEY;
        return config;
    }
}